var express = require("express");
var router = express.Router();
const db = require("../model/db");
var multiparty = require("multiparty");
/* 获取门店信息+门店名称搜索 */
router.get("/getStoreList", function (req, res, next) {
  let name = req.query.name;
  if (name) {
    let sql = `SELECT store.*,COALESCE(COUNT(staff.sid), 0) AS count,COALESCE(COUNT(vehicle.sid), 0) AS carCount FROM store
    LEFT JOIN staff ON store.id = staff.sid
    LEFT JOIN vehicle ON store.id = vehicle.sid where store.name like '%${name}%'
    GROUP BY store.id;`;
    db.query(sql, function (err, result) {
      if (err) {
        console.log(err, "获取数据出错了");
      } else {
        // 给每个节点添加一个唯一key
        result.forEach((item) => {
          item["key"] = item.id;
        });
        res.send({ code: 200, msg: "获取成功", data: result });
      }
    });
  } else {
    let sql = `SELECT store.*,COALESCE(COUNT(staff.sid), 0) AS count,COALESCE(COUNT(vehicle.sid), 0) AS carCount FROM store
    LEFT JOIN staff ON store.id = staff.sid
    LEFT JOIN vehicle ON store.id = vehicle.sid
    GROUP BY store.id;
`;
    db.query(sql, function (err, result) {
      if (err) {
        console.log(err, "获取数据出错了");
      } else {
        // 给每个节点添加一个唯一key
        result.forEach((item) => {
          item["key"] = item.id;
        });
        res.send({ code: 200, msg: "获取成功", data: result });
      }
    });
  }
});

// 根据门店状态搜索
router.get("/searchSelect", function (req, res) {
  let status = req.query.status;
  console.log(status, "状态··············");
  if (status) {
    let sql = `SELECT store.*,COALESCE(COUNT(staff.sid), 0) AS count,COALESCE(COUNT(vehicle.sid), 0) AS carCount FROM store
    LEFT JOIN staff ON store.id = staff.sid
    LEFT JOIN vehicle ON store.id = vehicle.sid where store.status='${status}'
    GROUP BY store.id;`;
    db.query(sql, function (err, result) {
      if (err) {
        console.log(err, "获取数据出错了");
      } else {
        // 给每个节点添加一个唯一key
        result.forEach((item) => {
          item["key"] = item.id;
        });
        res.send({ code: 200, msg: "获取成功", data: result });
      }
    });
  } else {
    let sql = `SELECT store.*,COALESCE(COUNT(staff.sid), 0) AS count,COALESCE(COUNT(vehicle.sid), 0) AS carCount FROM store
    LEFT JOIN staff ON store.id = staff.sid
    LEFT JOIN vehicle ON store.id = vehicle.sid
    GROUP BY store.id;
`;
    db.query(sql, function (err, result) {
      if (err) {
        console.log(err, "获取数据出错了");
      } else {
        // 给每个节点添加一个唯一key
        result.forEach((item) => {
          item["key"] = item.id;
        });
        res.send({ code: 200, msg: "获取成功", data: result });
      }
    });
  }
});

// 门店添加
router.post("/addStore", (req, res) => {
  let body = req.body;
  console.log(body);
  let sql = `insert into store(name,address,detailAds,people,tell,time,lon,lat,setLon,setLat) values('${body.name}','${body.address}','${body.detailAds}','${body.people}','${body.tell}','${body.time}','${body.lon}','${body.lat}','${body.lon}','${body.lat}');`;
  db.query(sql, function (err, result) {
    console.log(err, "错误············");
    if (result.affectedRows > 0) {
      res.send({ code: 200, msg: "添加成功" });
    }
  });
});

// 修改门店信息
router.post("/editStore", (req, res) => {
  let body = req.body;
  console.log(body);
  let sql = `
  UPDATE store
  SET name = '${body.name}',address = '${body.address}',detailAds = '${body.detailAds}',people = '${body.people}',tell = '${body.tell}'
  WHERE id=${body.id};
  `;
  db.query(sql, function (err, result) {
    if (result.affectedRows > 0) {
      res.send({ code: 200, msg: "修改成功" });
    }
  });
});

// 删除门店
router.get("/deleteStore", (req, res) => {
  let id = req.query.id;
  let sql = `delete from store where id=${id}`;
  db.query(sql, function (err, result) {
    if (result.affectedRows > 0) {
      res.send({ code: 200, msg: "删除成功" });
    } else {
      res.send({ code: 500, msg: "删除失败" });
    }
  });
});

// 修改门店服务
router.post("/editStoreSetting", (req, res) => {
  let body = req.body;
  let sql = `update store set lon='${body.lon}', lat='${body.lat}' where id=${body.id}`;
  db.query(sql, function (err, result) {
    if (result.affectedRows > 0) {
      res.send({ code: 200, msg: "修改成功" });
    }
  });
});

// 修改还车范围
router.post("/editStoreSetting", (req, res) => {
  let body = req.body;
  let sql = `update store set setLon='${body.lon}', setLat='${body.lat}' where id=${body.id}`;
  db.query(sql, function (err, result) {
    if (result.affectedRows > 0) {
      res.send({ code: 200, msg: "修改成功" });
    }
  });
});

// 获取员工信息
router.get("/getStaffList", (req, res) => {
  let name = req.query.name;
  if (name) {
    let sql = `select staff.*,store.name as storeName,keyPost.name as postName from staff,store,keyPost where staff.sid=store.id and staff.kid=keyPost.id and staff.name like '%${name}%'`;
    db.query(sql, function (err, result) {
      if (result.length > 0) {
        result.forEach((item) => {
          item["key"] = item.id;
        });
        res.send({ code: 200, msg: "获取成功", data: result });
      } else {
        res.send({ code: 500, msg: "获取失败" });
      }
    });
  } else {
    let sql = `select staff.*,store.name as storeName,keyPost.name as postName from staff,store,keyPost where staff.sid=store.id and staff.kid=keyPost.id`;
    db.query(sql, function (err, result) {
      if (result.length > 0) {
        result.forEach((item) => {
          item["key"] = item.id;
        });
        res.send({ code: 200, msg: "获取成功", data: result });
      } else {
        res.send({ code: 500, msg: "获取失败" });
      }
    });
  }
});

// 获取门店名称
router.get("/getStoreName", (req, res) => {
  let sql = "select * from store";
  db.query(sql, function (err, result) {
    if (result.length > 0) {
      res.send({ code: 200, msg: "获取成功", data: result });
    } else {
      res.send({ code: 500, msg: "获取失败" });
    }
  });
});

// 获取门店下的对应员工
router.get("/getStoreStaff", (req, res) => {
  let id = req.query.id;
  console.log(id, "id·················");
  let sql = `select staff.*,store.name as storeName,keyPost.name as postName from staff,store,keyPost where staff.sid=store.id and staff.kid=keyPost.id and staff.sid=${id}`;
  db.query(sql, function (err, result) {
    // console.log(err);
    if (result.length > 0) {
      result.forEach((item) => {
        item["key"] = item.id;
      });
      res.send({ code: 200, msg: "获取成功", data: result });
    } else {
      res.send({ code: 500, msg: "获取失败" });
    }
  });
});

// 获取岗位
router.get("/getKeyPost", (req, res) => {
  let sql = "select * from keyPost";
  db.query(sql, (err, result) => {
    if (result.length > 0) {
      result.forEach((item) => {
        item["key"] = item.id;
        (item.value = item.id), (item.label = item.name);
      });
      res.send({ code: 200, msg: "获取成功", data: result });
    }
  });
});

// 添加员工
router.post("/addStaff", (req, res) => {
  let body = req.body;
  let sql = `insert into staff(name,sid,tell,kid) values('${body.name}','${body.sid}','${body.tell}','${body.kid}')`;
  db.query(sql, (err, result) => {
    if (result.affectedRows > 0) {
      res.send({ code: 200, msg: "添加成功" });
    } else {
      res.send({ code: 500, msg: "添加失败" });
    }
  });
});
// 修改员工
router.post("/editStaff", (req, res) => {
  let body = req.body;
  console.log(body, "body");
  let sql2 = `update staff set name='${body.name}',sid='${body.sid}',kid='${body.kid}',tell='${body.tell}' where id=${body.id};`;
  db.query(sql2, (err, result) => {
    console.log(err);
    if (result.affectedRows > 0) {
      res.send({ code: 200, msg: "修改成功" });
    } else {
      res.send({ code: 500, msg: "修改失败" });
    }
  });
});
// 删除员工
router.get("/deleteStaff", (req, res) => {
  let id = req.query.id;
  let sql = `delete from staff where id=${id}`;
  db.query(sql, function (err, result) {
    if (result.affectedRows > 0) {
      res.send({ code: 200, msg: "删除成功" });
    } else {
      res.send({ code: 500, msg: "删除失败" });
    }
  });
});

// 上传图片
router.post("/upload", (req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = "upload";
  form.parse(req, (err, formData, imgData) => {
    console.log("http://localhost:3100/" + imgData.avatar[0].path);
    res.send({
      code: 200,
      path: "http://localhost:3100/" + imgData.avatar[0].path,
    });
  });
});

// 获取个人客户
router.get("/getCustomList", (req, res) => {
  let name = req.query.name;
  if (name) {
  } else {
    let sql =
      "SELECT custom.*,COALESCE(COUNT(`order`.uid), 0) AS count FROM custom left join `order` on custom.id = `order`.uid where custom.qid is null and flag=false GROUP BY custom.id;";
    db.query(sql, (err, result) => {
      if (!err) {
        result.forEach((item) => {
          item["key"] = item.id;
        });
        res.send({ code: 200, msg: "获取成功", data: result });
      } else {
        res.send({ code: 500, msg: "获取失败" });
      }
    });
  }
});

// 添加个人客户
router.post("/addCustom", (req, res) => {
  let body = req.body;
  if (body.id) {
    let sql = `update custom set name='${body.name}',jinName='${body.Jinname}',jinTel='${body.Jintel}',sfz='${body.sfz}',tell='${body.tell}',photo_z='${body.photo_z}',photo_f='${body.photo_f}',driver_z='${body.driver_z}',driver_f='${body.driver_f}' where id=${body.id};`;
    db.query(sql, (err, result) => {
      if (result.affectedRows > 0) {
        res.send({ code: 200, msg: "修改成功" });
      } else {
        res.send({ code: 500, msg: "修改失败" });
      }
    });
  } else {
    let sql = `insert into custom(name,sfz,tell,photo_z,photo_f,driver_z,driver_f,jinName,jinTel) values('${body.name}','${body.sfz}','${body.tell}','${body.photo_z}','${body.photo_f}','${body.driver_z}','${body.driver_f}','${body.Jinname}','${body.Jintel}');`;
    db.query(sql, (err, result) => {
      if (result.affectedRows > 0) {
        res.send({ code: 200, msg: "添加成功" });
      } else {
        res.send({ code: 500, msg: "添加失败" });
      }
    });
  }
});

// 获取租赁信息
router.get("/getZuList", (req, res) => {
  let id = req.query.id;
  let sql =
    "select `order`.createTime,`order`.id,`order`.oid,`order`.rent,orderState.name,vehiclemodel.brand,vehiclemodel.cxname,vehiclemodel.TransmissionType,vehiclemodel.seats from `order`,orderState,vehiclemodel where `order`.state=orderState.id and `order`.mid=vehiclemodel.cid and `order`.uid=" +
    id;
  db.query(sql, (err, result) => {
    if (!err) {
      result.forEach((item) => {
        item["key"] = item.id;
      });
      res.send({ code: 200, msg: "获取成功", data: result });
    } else {
      res.send({ code: 500, msg: "获取失败" });
    }
  });
});

// 拉黑客户
router.get("/blackUser", (req, res) => {
  let id = req.query.id;
  let sql = "update custom set flag=true where id=" + id;
  db.query(sql, (err, result) => {
    if (result.affectedRows > 0) {
      res.send({ code: 200, msg: "已将用户拉至黑名单" });
    } else {
      res.send({ code: 500, msg: "拉黑用户失败" });
    }
  });
});

// 获取黑名单客户
router.get("/getBlackList", (req, res) => {
  let sql =
    "SELECT custom.*,COALESCE(COUNT(`order`.uid), 0) AS count FROM custom left join `order` on custom.id = `order`.uid where custom.qid is null and flag=true GROUP BY custom.id;";
  db.query(sql, (err, result) => {
    if (!err) {
      result.forEach((item) => {
        item["key"] = item.id;
      });
      res.send({ code: 200, msg: "获取成功", data: result });
    } else {
      res.send({ code: 500, msg: "获取失败" });
    }
  });
});

// 拉黑客户
router.get("/removeBlack", (req, res) => {
  let id = req.query.id;
  let sql = "update custom set flag=false where id=" + id;
  db.query(sql, (err, result) => {
    if (result.affectedRows > 0) {
      res.send({ code: 200, msg: "已将用户移除黑名单" });
    } else {
      res.send({ code: 500, msg: "移除失败" });
    }
  });
});

module.exports = router;
